<template>
  <div style="height: 97%">
    <div class="head">
      <a-radio-group v-model:value="courseStatusFilter" button-style="solid" @change="handleStatusFilterChange">
        <a-space size="middle">
          <a-radio-button :value="null">所有课程</a-radio-button>
          <a-radio-button :value="0">未开课</a-radio-button>
          <a-radio-button :value="1">进行中</a-radio-button>
          <a-radio-button :value="2">已结课</a-radio-button>
        </a-space>

        <div style="margin-right: 25px; float: right">
          <a-button type="primary" @click="createCourseVisible = true">新增课程</a-button>
          <a-button style="margin-left: 10px" @click="linkUserToCourses" :loading="linking">关联课程</a-button>
        </div>
      </a-radio-group>
    </div>

    <div class="body">
      <!-- 筛选栏 -->
      <a-form
        class="filter"
        ref="formRef"
        :model="formState"
        autocomplete="off"
        :label-col="labelCol"
      >
        <div class="filter-box">
          <div class="filter-options">
            <a-form-item label="课程名称" name="CourseName">
              <a-input
                v-model:value="formState.CourseName"
                placeholder="输入课程名称"
                allow-clear
              />
            </a-form-item>
            
            <a-form-item label="排序" name="sortField">
              <a-select v-model:value="formState.sortField" style="width: 200px">
                <a-select-option value="courseName">课程名称</a-select-option>
                <a-select-option value="createTime">创建时间</a-select-option>
                <a-select-option value="courseStatus">课程状态</a-select-option>
              </a-select>
              <a-radio-group v-model:value="formState.sortOrder" button-style="solid" style="margin-left: 10px">
                <a-radio-button value="asc">升序</a-radio-button>
                <a-radio-button value="desc">降序</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </div>

          <div class="filter-buttons">
            <a-button type="primary" @click="onSubmit">
              <template #icon> <SearchOutlined /> </template>查询</a-button
            >
            <a-button @click="resetForm">
              <template #icon> <RedoOutlined /> </template>重置</a-button
            >
          </div>
        </div>
      </a-form>
      <!-- 表格 -->
      <CourseTableTable 
        :courses="courses" 
        :loading="loading" 
        @edit-course="handleEditCourse" 
        @delete-course="handleDeleteCourse"
        @status-change="handleStatusChange"
        @batch-delete="handleBatchDelete"
        @batch-status-change="handleBatchStatusChange" 
      />
      <!-- 分页器 -->
      <a-pagination
        v-model:current="current"
        v-model:page-size="pageSizeRef"
        :total="total"
        show-size-changer
        class="pagination"
      />
    </div>

    <!-- 新建课程弹窗 -->
    <CreateCourses v-model:modelVisible="createCourseVisible" @course-created="handleCourseCreated" />
    
    <!-- 编辑课程弹窗 -->
    <EditCourses v-model:modelVisible="editCourseVisible" :courseId="selectedCourseId" :courseData="selectedCourseData" @course-updated="handleCourseUpdated" />
  </div>
</template>

<script lang="ts" setup>
import CourseTableTable from '@/views/CoursesList/CourseTable.vue';
import CreateCourses from '@/views/CoursesList/CreateCourses.vue';
import EditCourses from '@/views/CoursesList/EditCourses.vue';
import { ref, reactive, onMounted } from 'vue';
import { SearchOutlined, RedoOutlined } from '@ant-design/icons-vue';
import type { FormInstance } from 'ant-design-vue';
import dayjs from 'dayjs';
import CourseDao from '@/daos/course_dao';
import { useStore } from 'vuex';
import { message } from 'ant-design-vue';

const store = useStore();
const courseDao = new CourseDao();
//创建课程窗口状态
const createCourseVisible = ref<boolean>(false);
//编辑课程窗口状态
const editCourseVisible = ref<boolean>(false);
const selectedCourseId = ref(null);
const selectedCourseData = ref({});

//顶部项目类型选取值
const projectTyep = ref(null);
//课程状态筛选
const courseStatusFilter = ref(null);
//分页器
const current = ref(1);
const pageSizeRef = ref(10);
const total = ref();

//筛选表单对应数据接口
interface FormState {
  CourseName: string;
  sortField: string;
  sortOrder: string;
}
//筛选标签宽度
const labelCol = { style: { width: '90px' } };
//筛选表单对应数据
const formState = reactive<FormState>({
  CourseName: '',
  sortField: 'createTime',
  sortOrder: 'desc'
});

//筛选表单Ref
const formRef = ref<FormInstance>();
//项目表格数据与加载状态
const courses = ref([]);
const loading = ref(true);
//提交筛选内容
const onSubmit = () => {
  findCourses(1, formState.CourseName);
};
//清空筛选框内容
const resetForm = () => {
  formRef.value.resetFields();
  findCourses(1, null);
};

// 处理状态筛选变化
const handleStatusFilterChange = () => {
  findCourses(1, formState.CourseName);
};

const linking = ref(false);

const findCourses = (current: number, courseName: string = null) => {
  loading.value = true;
  console.log('开始获取课程列表，参数:', {
    userId: store.getters.userId, 
    courseName, 
    current: current - 1, 
    pageSize: pageSizeRef.value
  });
  
  courseDao
    .findCoursesByUserId(store.getters.userId, courseName, current - 1, pageSizeRef.value)
    .then((result) => {
      console.log('课程列表接口返回：', result);
      
      // 检查返回数据格式并进行适当处理
      let coursesData = [];
      if (result && result.data && result.data.data) {
        coursesData = result.data.data.rows || [];
        total.value = result.data.data.totalCount || 0;
        console.log('解析课程数据成功，数量:', coursesData.length);
      } else {
        console.error('课程数据格式异常:', result);
      }
      
      // 如果有状态筛选，则过滤结果
      if (courseStatusFilter.value !== null) {
        coursesData = coursesData.filter(
          course => course.courseStatus === courseStatusFilter.value
        );
        // 更新总数（用于分页显示）
        total.value = coursesData.length;
      }
      
      // 应用排序
      if (formState.sortField && coursesData.length > 0) {
        coursesData.sort((a, b) => {
          let comparison = 0;
          
          // 根据不同字段进行比较
          if (formState.sortField === 'courseName') {
            comparison = a.courseName ? a.courseName.localeCompare(b.courseName || '') : 0;
          } else if (formState.sortField === 'createTime') {
            const dateA = a.createTime ? new Date(a.createTime).getTime() : 0;
            const dateB = b.createTime ? new Date(b.createTime).getTime() : 0;
            comparison = dateA - dateB;
          } else if (formState.sortField === 'courseStatus') {
            const statusA = a.courseStatus !== undefined ? a.courseStatus : 0;
            const statusB = b.courseStatus !== undefined ? b.courseStatus : 0;
            comparison = statusA - statusB;
          }
          
          // 应用排序方向
          return formState.sortOrder === 'asc' ? comparison : -comparison;
        });
      }
      
      courses.value = coursesData;
      loading.value = false;
    })
    .catch((error) => {
      console.error('获取课程列表错误 findCourseByUserId', error);
      message.error('获取课程列表失败，请稍后重试');
      loading.value = false;
    });
};

// 课程创建成功后的回调函数
const handleCourseCreated = () => {
  findCourses(current.value);
};

// 编辑课程处理函数
const handleEditCourse = (course) => {
  selectedCourseId.value = course.courseId;
  selectedCourseData.value = course;
  editCourseVisible.value = true;
};

// 课程更新成功后的回调函数
const handleCourseUpdated = () => {
  findCourses(current.value);
};

// 处理删除课程
const handleDeleteCourse = (course) => {
  loading.value = true;
  courseDao.deleteCourse(course.courseId)
    .then(result => {
      if (result.data.code === 200) {
        message.success('删除课程成功');
        findCourses(current.value);
      } else {
        message.error(result.data.msg || '删除课程失败');
      }
      loading.value = false;
    })
    .catch(error => {
      console.error('删除课程出错', error);
      message.error('删除课程失败: ' + (error.message || '未知错误'));
      loading.value = false;
    });
};

// 处理课程状态变更
const handleStatusChange = (data) => {
  loading.value = true;
  courseDao.updateCourseStatus(data.courseId, data.status)
    .then(result => {
      if (result.data.code === 200) {
        message.success('课程状态更新成功');
        // 刷新课程列表
        findCourses(current.value, formState.CourseName);
      } else {
        message.error(result.data.msg || '更新课程状态失败');
        loading.value = false;
      }
    })
    .catch(error => {
      console.error('更新课程状态出错', error);
      message.error('更新课程状态失败: ' + (error.message || '未知错误'));
      loading.value = false;
    });
};

// 处理批量删除
const handleBatchDelete = (courseIds) => {
  if (!courseIds || courseIds.length === 0) {
    return;
  }
  
  loading.value = true;
  
  // 创建删除请求的Promise数组
  const deletePromises = courseIds.map(courseId => 
    courseDao.deleteCourse(courseId)
  );
  
  // 并行执行所有删除请求
  Promise.all(deletePromises)
    .then(results => {
      // 检查所有结果
      const failedCount = results.filter(r => r.data.code !== 200).length;
      
      if (failedCount === 0) {
        message.success(`成功删除 ${courseIds.length} 个课程`);
      } else if (failedCount < courseIds.length) {
        message.warning(`部分课程删除失败：${failedCount}/${courseIds.length}`);
      } else {
        message.error('所有课程删除失败');
      }
      
      // 刷新课程列表
      findCourses(current.value, formState.CourseName);
    })
    .catch(error => {
      console.error('批量删除课程出错', error);
      message.error('批量删除课程失败: ' + (error.message || '未知错误'));
      loading.value = false;
    });
};

// 处理批量状态更新
const handleBatchStatusChange = (data) => {
  if (!data.courseIds || data.courseIds.length === 0) {
    return;
  }
  
  loading.value = true;
  
  // 创建状态更新请求的Promise数组
  const updatePromises = data.courseIds.map(courseId => 
    courseDao.updateCourseStatus(courseId, data.status)
  );
  
  // 并行执行所有更新请求
  Promise.all(updatePromises)
    .then(results => {
      // 检查所有结果
      const failedCount = results.filter(r => r.data.code !== 200).length;
      
      if (failedCount === 0) {
        message.success(`成功更新 ${data.courseIds.length} 个课程状态`);
      } else if (failedCount < data.courseIds.length) {
        message.warning(`部分课程状态更新失败：${failedCount}/${data.courseIds.length}`);
      } else {
        message.error('所有课程状态更新失败');
      }
      
      // 刷新课程列表
      findCourses(current.value, formState.CourseName);
    })
    .catch(error => {
      console.error('批量更新课程状态出错', error);
      message.error('批量更新课程状态失败: ' + (error.message || '未知错误'));
      loading.value = false;
    });
};

// 关联用户到所有课程
const linkUserToCourses = () => {
  if (!store.getters.userId) {
    message.error('未获取到用户ID');
    return;
  }
  
  linking.value = true;
  courseDao
    .linkUserToAllCourses(store.getters.userId)
    .then((result) => {
      console.log('关联课程结果:', result);
      if (result.data.code === 200) {
        message.success(result.data.msg || '关联课程成功');
        // 刷新课程列表
        findCourses(current.value);
      } else {
        message.error(result.data.msg || '关联课程失败');
      }
    })
    .catch((error) => {
      console.error('关联课程失败:', error);
      message.error('关联课程失败，请稍后重试');
    })
    .finally(() => {
      linking.value = false;
    });
};

//挂载页面数据
onMounted(() => {
  console.log('我的课程组件加载，当前用户ID:', store.getters.userId);
  // 在组件加载时加载课程列表
  findCourses(current.value);
});
</script>

<style scoped>
.head {
  display: flex;
  flex-direction: column;
  padding: 1.5%;
  margin: 1%;
  height: auto;
  /* 使容器高度为视口高度 */
  max-width: 100%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border: 1px solid lightgray;
  border-radius: 10px;
  background-color: #fff;
  overflow: auto;
}

.body {
  display: flex;
  flex-direction: column;
  padding: 1.5%;
  margin: 1%;
  height: 85%;
  /* 使容器高度为视口高度 */
  max-width: 100%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border: 1px solid lightgray;
  border-radius: 10px;
  background-color: #fff;
  overflow: auto;
}

.filter {
  padding: 5px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-box {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  width: 75%;
}

.filter-buttons {
  display: flex;
  justify-content: space-between;
  width: 180px;
}

.pagination {
  text-align: center;
  bottom: 0%;
  margin-top: 1%;
}
</style>
